﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;
using School.Entities;
using School.Organization;
using School.Common;

namespace School.Pages.Organization
{
    public partial class Departments : System.Web.UI.Page
    {        
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((IQueryable<int>)Session["privilage"] != null)
            {
                var xx = (IQueryable<int>)Session["privilage"];

                if (xx.Contains(1303) == true)
                {                   
                    GridView1.DataSource = Department.All().Select(x => new { x.Id, x.Name, x.Description, CName = x.ORG_Campus.Name });
                    GridView1.DataBind();

                    LstCampuse.DataSource = School.Common.Structure.GetCampuses();
                    LstCampuse.DataValueField = "Id";
                    LstCampuse.DataTextField = "Name";
                    LstCampuse.DataBind();

                    int id = 0;

                    if (int.TryParse(Request.QueryString["Id"], out id) && !IsPostBack)
                    {
                        var d = Department.Single(id);

                        if (d != null)
                        {
                            LstCampuse.SelectedValue = d.Campus_Id.ToString();
                            TxtName.Text = d.Name;
                            TxtDescription.Text = d.Description;
                        }
                        else
                        {
                            Response.Redirect("Departments.aspx");
                        }
                    }
                }
                else
                    Response.Redirect("../organization/no_privelege.aspx");
            }
            else
                Response.Redirect("../organization/no_privelege.aspx");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            int id = 0;

            if (int.TryParse(Request.QueryString["Id"], out id))
                Department.Update(new ORG_Department() { Id = id, Campus_Id = int.Parse(LstCampuse.SelectedValue), Name = TxtName.Text, Description = TxtDescription.Text });
            else
                Department.Add(new ORG_Department() { Campus_Id = int.Parse(LstCampuse.SelectedValue), Name = TxtName.Text, Description = TxtDescription.Text });

            Response.Redirect("Departments.aspx");
        }
    }
}